package com.sky.service.impl;

import com.aliyuncs.http.HttpResponse;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportSrevice;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportSreviceImpl implements ReportSrevice {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 统计营业额数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverData(LocalDate begin, LocalDate end) {
        List<LocalDate> list = new ArrayList<>();
        list.add(begin);
        while (!end.equals(begin)) {
            begin = begin.plusDays(1);
            list.add(begin);
        }
        List<Double> list1 = new ArrayList<>();
        list.forEach(item->{
            LocalDateTime beginTime = LocalDateTime.of(item, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(item, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double v = reportMapper.selectCountByMap(map);
            v = v == null ?  0.0 : v;
            list1.add(v);

        });
        return TurnoverReportVO.builder().dateList(StringUtils.join(list,","))
                .turnoverList(StringUtils.join(list1,",")).build();

    }

    @Override
    public UserReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> list = new ArrayList<>();
        list.add(begin);
        while (!end.equals(begin)) {
            begin = begin.plusDays(1);
            list.add(begin);
        }
        List<Integer> nowPeople = new ArrayList<>();
        List<Integer> totalPeople = new ArrayList<>();
        list.forEach(item->{
            LocalDateTime beginTime = LocalDateTime.of(item, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(item, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("end",endTime);
            Integer total = orderMapper.getCount(map);
            map.put("begin",beginTime);
            Integer count = orderMapper.getCount(map);
            nowPeople.add(count);
            totalPeople.add(total);
        });

        return UserReportVO.builder().dateList(StringUtils.join(list,","))
                .totalUserList(StringUtils.join(totalPeople,","))
                .newUserList(StringUtils.join(nowPeople,",")).build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!end.equals(begin)) {
            begin =begin.plusDays(1);
            dateList.add(begin);
        }
        //订单完成率
        Double orderCompletionRate = 0.0;
        //订单总数
        Integer totalOrderCount = 0;
        //有效订单数
        Integer validOrderCount = 0;
        //订单数列表
        List<Integer> orderCountList = new ArrayList<>();
        //有效订单数列表
        List<Integer> validOrderCountList = new ArrayList<>();
        dateList.forEach(item -> {
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            orderCountList.add(orderMapper.getOrderCount(map));
            map.put("status",Orders.COMPLETED);
            validOrderCountList.add(orderMapper.getOrderCount(map))  ;
        });
//        for(Integer integer : orderCountList) {
//            totalOrderCount += integer;
//        }
        totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //stream流形式
        validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        orderCompletionRate =0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue()/totalOrderCount.doubleValue();

        }

        return new OrderReportVO().builder()
                .dateList(StringUtils.join(dateList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .totalOrderCount(totalOrderCount)
                .build();
    }

    @Override
    public SalesTop10ReportVO getTopTen(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<Map<String,Object>> map = reportMapper.getTopTen(beginTime,endTime);
        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : map) {
            nameList.add((String) stringObjectMap.get("name"));
//            numberList.add(String.valueOf(stringObjectMap.get("number")));
            numberList.add( stringObjectMap.get("number").toString());
        }
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 到处运营数据报表
     * @param response
     */
    @Override
    public void getReport(HttpServletResponse response) {
        //先设置时间
        LocalDate now = LocalDate.now();
        LocalDateTime beginTime = LocalDateTime.of(now.minusDays(30), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(now.minusDays(1), LocalTime.MAX);
        //查询数据库
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);
        //通过poi将数据写入文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        //获取POI的工作簿对象
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            sheet1.getRow(1).getCell(1).setCellValue("时间"+beginTime+"至"+endTime);
            sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
            LocalDate begin = now.minusDays(30);
            //遍历写入每日数据
            for (int i = 0; i < 30; i++) {
                LocalDate time = begin.plusDays(i);
                XSSFRow row = sheet1.getRow(i + 7);
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(time, LocalTime.MIN), LocalDateTime.of(time, LocalTime.MAX));
                row.getCell(1).setCellValue(time.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());
            }


            //获取输出流
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            out.close();
            excel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
